<template>
    <div id="CesiumContainer">
        <div class="button">
            <el-button type="danger" round @click="loadSimple">Simple</el-button>
            <el-button type="danger" round @click="loadSatellites">Satellites</el-button>
            <el-button type="danger" round @click="locateView">定位</el-button>
        </div>
    </div>
</template>

<script>
import * as Cesium from "cesium";
import "/node_modules/cesium/Build/Cesium/Widgets/widgets.css";

Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhOTM4NmM2ZC0yNzQ3LTRjYTQtYWMxZC00YjJlOWQ5ZGNjYTQiLCJpZCI6Mjc2NjA1LCJpYXQiOjE3Mzk3Nzk2NjJ9.a-ivPAeqR5CXISd0Y2Pm_lAp1q7fpLPc3a8NWLXvreA';

export default {
    data() {
        return {
            viewer: null,
            boatEntity: null,
            satelliteEntities: [],
            connectionRadius: 5000000,
            beamEntities: []
        };
    },
    mounted() {
        this.initCesium();
    },
    methods: {
        initCesium() {
            try {
                this.viewer = new Cesium.Viewer("CesiumContainer", {
                    shouldAnimate: true,
                    timeline: true,
                    animation: true
                });
                this.createBoatModel("/model/boat.glb", 0);
            } catch (error) {
                console.error('Cesium Viewer 初始化失败:', error);
            }
        },

        locateView() {
            this.viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(125, 15, 1000000),
                orientation: {
                    heading: Cesium.Math.toRadians(0),
                    pitch: Cesium.Math.toRadians(-30),
                    roll: 0,
                },
                duration: 3,
                easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
            });
        },

        createBoatModel(url, height) {
            const position = Cesium.Cartesian3.fromDegrees(125, 30, height);
            const heading = Cesium.Math.toRadians(135);
            const hpr = new Cesium.HeadingPitchRoll(heading, 0, 0);
            const orientation = Cesium.Transforms.headingPitchRollQuaternion(position, hpr);

            this.boatEntity = this.viewer.entities.add({
                name: "Boat",
                position: position,
                orientation: orientation,
                model: {
                    uri: url,
                    minimumPixelSize: 128,
                    maximumScale: 200000,
                },
            });

            this.checkSatelliteConnections();
        },

        loadSatellites() {
            this.clearExistingBeams();
            if (this.viewer) {
                this.viewer.dataSources.add(
                    Cesium.CzmlDataSource.load("czml/qianfan.czml")
                ).then((dataSource) => {
                    this.satelliteEntities = dataSource.entities.values;
                    this.viewer.clock.shouldAnimate = true;
                    this.viewer.clock.multiplier = 2;
                    this.checkSatelliteConnections();
                });
            }
        },

        checkSatelliteConnections() {
            this.clearExistingBeams();
            if (this.boatEntity && this.satelliteEntities.length > 0) {
                const currentTime = this.viewer.clock.currentTime;
                this.satelliteEntities.forEach((satellite) => {
                    const boatPos = this.boatEntity.position.getValue(currentTime);
                    const satPos = satellite.position.getValue(currentTime);

                    if (!boatPos || !satPos) return;

                    const distance = Cesium.Cartesian3.distance(boatPos, satPos);
                    if (distance <= this.connectionRadius) {
                        this.createBeamConnection(boatPos, satPos, distance);
                    }
                });
            }
        },

        createBeamConnection(startPos, endPos, distance) {
            console.log("createBeamConnection");

            // 计算方向向量
            const direction = Cesium.Cartesian3.subtract(endPos, startPos, new Cesium.Cartesian3());
            Cesium.Cartesian3.normalize(direction, direction);

            // 定义波束的横截面（圆形）
            const radius = Math.tan(Cesium.Math.toRadians(0.5)) * distance; // 根据角度计算半径
            const shape = [];
            for (let i = 0; i < 360; i += 10) {
                const angle = Cesium.Math.toRadians(i);
                shape.push(new Cesium.Cartesian2(
                    radius * Math.cos(angle),
                    radius * Math.sin(angle)
                ));
            }

            // 使用 PolylineVolume 模拟波束
            const beamEntity = this.viewer.entities.add({
                polylineVolume: {
                    positions: [startPos, endPos], // 波束的路径
                    shape: shape, // 横截面形状
                    material: new Cesium.ColorMaterialProperty(
                        Cesium.Color.CYAN.withAlpha(0.3) // 波束颜色
                    ),
                    outline: true,
                    outlineColor: Cesium.Color.CYAN.withAlpha(0.5)
                }
            });
            console.log(beamEntity);

            // 创建辅助连线
            const lineEntity = this.viewer.entities.add({
                polyline: {
                    positions: [startPos, endPos],
                    width: 1,
                    material: new Cesium.PolylineGlowMaterialProperty({
                        glowPower: 0.2,
                        color: Cesium.Color.CYAN.withAlpha(0.5)
                    })
                }
            });

            this.beamEntities.push(beamEntity, lineEntity);
        },

        clearExistingBeams() {
            this.beamEntities.forEach(entity => this.viewer.entities.remove(entity));
            this.beamEntities = [];
        },

        loadSimple() {
            this.clearExistingBeams();
            if (this.viewer) {
                this.viewer.dataSources.add(
                    Cesium.CzmlDataSource.load("czml/simple.czml")
                );
            }
        }
    }
};
</script>

<style scoped>
#CesiumContainer {
    height: 100%;
    width: 100%;
    position: relative;
}

.button {
    position: absolute;
    z-index: 100;
    top: 20px;
    left: 20px;
    background: rgba(0, 0, 0, 0.7);
    padding: 10px;
    border-radius: 5px;
}

/* 波束辉光效果 */
.cesium-sensor-volume {
    filter: drop-shadow(0 0 8px rgba(0, 255, 255, 0.5));
}

/* 隐藏Cesium logo */
.cesium-widget-credits {
    display: none !important;
}
</style>